package com.zhibang.controller;

import com.zhibang.util.RedisUtil;
import com.zhibang.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.mail.internet.InternetAddress;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * @autor l
 * @date 2025年06月28日14:16
 */
@Tag(name = "邮件接口")
@RestController
public class EmailController {
    @Resource
    private JavaMailSender javaMailSender;//注入邮件工具类

    @Resource
    RedisUtil redisUtil;
    @PostMapping("send")
    public Result sendEmail(String toEmail){
        try {
            //true表示支持复杂类型
            MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            messageHelper.setFrom(new InternetAddress("l<3028160397@qq.com>"));
            //邮件收信人
            messageHelper.setTo(toEmail);
            //邮件主题
            messageHelper.setSubject("注册");
            //邮件内容
            //生成6位数验证码
            int code=(int)((Math.random()*9+1)*100000);
            messageHelper.setText("验证码是:"+ code);
            // 邮件发送时间
            messageHelper.setSentDate(new Date());
            //正式发送邮件
            javaMailSender.send(messageHelper.getMimeMessage());
            String uuid= UUID.randomUUID().toString();
            redisUtil.set("yzm:"+uuid,String.valueOf(code), 60*2);
            return Result.data(uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("发送失败");
        }
    }
    @PostMapping("verify")
    @Operation(summary = "验证")
    public Result verify(String uuid,String code){
        String yzm=(String)redisUtil.get("yzm:"+uuid);
        if(yzm==null){
            return Result.fail("验证码已过期");
        }
        if(!yzm.equals(code)){
            return Result.fail("验证码错误");
        }
        redisUtil.delete("yzm:"+uuid);
        return Result.ok("验证成功");
    }

}
